package org.atlantis.grosbeak.lang.stream;

import java.io.IOException;
import java.io.InputStream;

/**
 * 字符串输入流。会将读取到的内容填充到一个StringBuilder中。
 * 
 * @author <a href="mailto:seenoevil.cn@gmail.com">SeeNoEvil</a>
 * 
 */
public class StringInputStream extends InputStream {

	private char[] cs;
	private int cursor;
	private int mark;

	public StringInputStream() {
		super();
		cursor = 0;
		mark = 0;
	}

	public StringInputStream(CharSequence s) {
		this();
		if (null != cs)
			cs = s.toString().toCharArray();
		else
			cs = new char[0];
	}

	@Override
	public synchronized void mark(int readLimit) {
		this.mark = readLimit;
	}

	@Override
	public boolean markSupported() {
		return true;
	}

	@Override
	public int read() throws IOException {
		if (cursor >= cs.length)
			return -1;
		return cs[cursor++];
	}

	@Override
	public int available() throws IOException {
		return cs.length;
	}

	@Override
	public synchronized void reset() throws IOException {
		cursor = mark;
	}

	@Override
	public long skip(long n) throws IOException {
		int length = cs.length;
		if (length > cursor + n) {
			cursor += n;
			return n;
		}
		int d = length - 1 - cursor;
		cursor = length;
		return d;
	}
}
